﻿// Copyright (c) ZhangPeihang. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using LaserMark.Components.Services;
using LaserMark.Control.Service;
using LaserMark.DataAccess.Service;
using LaserMark.Print.Service;
using LaserMark.SuperDog;
using LaserMark.View.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Diagnostics;
using System.Windows;

namespace LaserMark.Views
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Init : Window
    {
        public string? text { get; set; } = "读取配置中...";

        [NotNull]
        private IServiceProvider? Service { get; set; }

        public Init()
        {
            InitializeComponent();
            Service = ((IServiceProvider)App.Current.FindResource("services"));
        }

        private void Init_OnLoaded(object sender, RoutedEventArgs e)
        {

            string name = Process.GetCurrentProcess().ProcessName;
            if (Process.GetProcessesByName(name).Length > 1)
            {
                MessageBox.Show("当前程序已启动");
                Application.Current.Shutdown();
            }
            else
            {
                Text.Text = text;
                var options = Service.GetRequiredService<IOptions<MarkOption>>().Value;
                var machineService = Service.GetRequiredService<IMachineService>();
                var deviceArgsService = Service.GetRequiredService<IDeviceArgsService>();
                var connect = Service.GetRequiredService<IConnectLineService>();
                var markArgsService = Service.GetRequiredService<IMarkArgsService>();
                var photoelectricityService = Service.GetRequiredService<IPhotoelectricityService>();
                var gCodeOrderService = Service.GetRequiredService<IGCodeOrderService>();
                var control = Service.GetRequiredService<IControl>();
                var globalStatus = Service.GetRequiredService<IGlobalStatus>();
                var print = Service.GetRequiredService<IPrint>();
                var codeTemplateService = Service.GetRequiredService<ICodeTemplateService>();
                var comprehensiveService = Service.GetRequiredService<IComprehensiveService>();
                var dogService = Service.GetRequiredService<IDogService>();
                MainWindow main = new MainWindow();
                Dispatcher.InvokeAsync(async () =>
                {

#if DEBUG
                    Text.Text = "读取机械参数...";
                    options.AxisCode = await machineService.GetMachine("AxisCode");
                    options.AxisCode = await machineService.GetMachine("AxisCode");
                    options.ZeroOffSet = await machineService.GetMachine("ZeroOffSet");
                    options.ZeroVel = await machineService.GetMachine("ZeroVel");
                    options.ZeroAcc = await machineService.GetMachine("ZeroAcc");
                    options.ZeroDec = await machineService.GetMachine("ZeroDec");
                    options.ManualVel = await machineService.GetMachine("ManualVel");
                    options.ManualAcc = await machineService.GetMachine("ManualAcc");
                    options.ManualDec = await machineService.GetMachine("ManualDec");
                    options.ScanVel = await machineService.GetMachine("ScanVel");
                    options.ScanAcc = await machineService.GetMachine("ScanAcc");
                    options.ScanDec = await machineService.GetMachine("ScanDec");
                    options.MarkVel = await machineService.GetMachine("MarkVel");
                    options.MarkAcc = await machineService.GetMachine("MarkAcc");
                    options.MarkDec = await machineService.GetMachine("MarkDec");
                    options.SoftMaxLimit = await machineService.GetMachine("ArrowMax");
                    options.SoftMinLimit = await machineService.GetMachine("NextMax");
                    options.AutoFolder = connect.Get("AutoFolder");
                    await Task.Delay(500);

                    Text.Text = "读取设备参数...";
                    options.XPluse.Value = (await machineService.GetMachine("GearRatio")).X;
                    options.YPluse.Value = (await machineService.GetMachine("GearRatio")).Y;
                    options.ZPluse.Value = (await machineService.GetMachine("GearRatio")).Z;
                    await Task.Delay(500);

                    Text.Text = "读取打码参数...";
                    options.MarkArgs = await markArgsService.GetMarks();
                    await Task.Delay(500);

                    Text.Text = "读取光电参数...";
                    options.PhotoelectricitySetting = await photoelectricityService.Get();
                    await Task.Delay(500);

                    Text.Text = "读取打码模板...";
                    options.MarkTemplate = await codeTemplateService.GetAll();
                    await Task.Delay(500);

                    options.GCodeOrder = await gCodeOrderService.GetAll();
                    options.ComprehensiveSetting = await comprehensiveService.Get();
                    var openControl = await control.Open(0, 0, 1);
                    if (openControl == 0)
                    {
                        var reset = await control.Rest(0);
                        if (reset == 0)
                        {
                            var load = await control.LoadConfig(0, "GTS800.cfg");
                            if (load == 0)
                            {
                                mc.GT_GetDi(0, mc.MC_GPI, out int value);
                                var status = Convert.ToString(value, 2);
                                if (status[13] == '1')
                                {
                                    await control.SetSoftLimit(0, (short)options.AxisCode.X, (int)options.SoftMaxLimit.X, (int)options.SoftMinLimit.X);
                                    await control.SetSoftLimit(0, (short)options.AxisCode.Y, (int)options.SoftMaxLimit.Y, (int)options.SoftMinLimit.Y);
                                    await control.SetSoftLimit(0, (short)options.AxisCode.Z, (int)options.SoftMaxLimit.Z, (int)options.SoftMinLimit.Z);
                                }

                                await control.ClearAxisStatus(0, (short)options.AxisCode.X, 1);
                                await control.ClearAxisStatus(0, (short)options.AxisCode.Y, 1);
                                await control.ClearAxisStatus(0, (short)options.AxisCode.Z, 1);

                                await control.AxisOn(0, (short)options.AxisCode.X);
                                await control.AxisOn(0, (short)options.AxisCode.Y);
                                await control.AxisOn(0, (short)options.AxisCode.Z);

                                await control.SetDoBit(0, mc.MC_GPO, 1, 0);

                                globalStatus.IsRunning = true; ;
                            }
                        }

                        main.Show();
                        this.Close();
                    }
                    else
                    {
                        main.Show();
                        this.Close();
                        //MessageBox.Show("找不到控制板卡");
                        //Application.Current.Shutdown();
                    }
#else
                    var res = await dogService.DogLogin("");
                    if (res)
                    {
                        var date = await dogService.GetExpDate();
                        var date1 = await dogService.GetTime();
                        var date2 = date - date1;
                        var day = date2.Days;
                        if (day >= 0)
                        {
                            if (day <= 7)
                            {
                                MessageBox.Show($"当前软件使用剩余天数为: {day}");
                            }
                            ManagementClass mc1 = new ManagementClass("Win32_NetworkAdapterConfiguration");
                            ManagementObjectCollection moc = mc1.GetInstances();
                            var maces = new List<string>();
                            foreach (var mo in moc)
                            {
                                var moAddress = mo.GetPropertyValue("MacAddress");
                                if (moAddress != null)
                                {
                                    var mac = moAddress.ToString();
                                    if (!string.IsNullOrEmpty(mac))
                                    {
                                        maces.Add(mac.Replace(":", "-"));
                                    }
                                }
                                mo.Dispose();
                            }

                            var mac1 = await dogService.GetMac();
                            if (!maces.Any(s => s.Equals(mac1, StringComparison.CurrentCultureIgnoreCase)))
                            {
                                MessageBox.Show("当前加密狗与软件不匹配");
                                Application.Current.Shutdown();
                            }
                            else
                            {
                                Text.Text = "读取机械参数...";
                                options.AxisCode = await machineService.GetMachine("AxisCode");
                                options.AxisCode = await machineService.GetMachine("AxisCode");
                                options.ZeroOffSet = await machineService.GetMachine("ZeroOffSet");
                                options.ZeroVel = await machineService.GetMachine("ZeroVel");
                                options.ZeroAcc = await machineService.GetMachine("ZeroAcc");
                                options.ZeroDec = await machineService.GetMachine("ZeroDec");
                                options.ManualVel = await machineService.GetMachine("ManualVel");
                                options.ManualAcc = await machineService.GetMachine("ManualAcc");
                                options.ManualDec = await machineService.GetMachine("ManualDec");
                                options.ScanVel = await machineService.GetMachine("ScanVel");
                                options.ScanAcc = await machineService.GetMachine("ScanAcc");
                                options.ScanDec = await machineService.GetMachine("ScanDec");
                                options.MarkVel = await machineService.GetMachine("MarkVel");
                                options.MarkAcc = await machineService.GetMachine("MarkAcc");
                                options.MarkDec = await machineService.GetMachine("MarkDec");
                                options.SoftMaxLimit = await machineService.GetMachine("ArrowMax");
                                options.SoftMinLimit = await machineService.GetMachine("NextMax");
                                options.AutoFolder = connect.Get("AutoFolder");
                                await Task.Delay(500);

                                Text.Text = "读取设备参数...";
                                options.XPluse.Value = (await machineService.GetMachine("GearRatio")).X;
                                options.YPluse.Value = (await machineService.GetMachine("GearRatio")).Y;
                                options.ZPluse.Value = (await machineService.GetMachine("GearRatio")).Z;
                                await Task.Delay(500);

                                Text.Text = "读取打码参数...";
                                options.MarkArgs = await markArgsService.GetMarks();
                                await Task.Delay(500);

                                Text.Text = "读取光电参数...";
                                options.PhotoelectricitySetting = await photoelectricityService.Get();
                                await Task.Delay(500);

                                Text.Text = "读取打码模板...";
                                options.MarkTemplate = await codeTemplateService.GetAll();
                                await Task.Delay(500);

                                options.GCodeOrder = await gCodeOrderService.GetAll();
                                options.ComprehensiveSetting = await comprehensiveService.Get();
                                var openControl = await control.Open(0, 0, 1);
                                if (openControl == 0)
                                {
                                    var reset = await control.Rest(0);
                                    if (reset == 0)
                                    {
                                        var load = await control.LoadConfig(0, "GTS800.cfg");
                                        if (load == 0)
                                        {
                                            mc.GT_GetDi(0, mc.MC_GPI, out int value);
                                            var status = Convert.ToString(value, 2);
                                            if (status[13] == '1')
                                            {
                                                await control.SetSoftLimit(0, (short)options.AxisCode.X, (int)options.SoftMaxLimit.X, (int)options.SoftMinLimit.X);
                                                await control.SetSoftLimit(0, (short)options.AxisCode.Y, (int)options.SoftMaxLimit.Y, (int)options.SoftMinLimit.Y);
                                                await control.SetSoftLimit(0, (short)options.AxisCode.Z, (int)options.SoftMaxLimit.Z, (int)options.SoftMinLimit.Z);
                                            }

                                            await control.ClearAxisStatus(0, (short)options.AxisCode.X, 1);
                                            await control.ClearAxisStatus(0, (short)options.AxisCode.Y, 1);
                                            await control.ClearAxisStatus(0, (short)options.AxisCode.Z, 1);

                                            await control.AxisOn(0, (short)options.AxisCode.X);
                                            await control.AxisOn(0, (short)options.AxisCode.Y);
                                            await control.AxisOn(0, (short)options.AxisCode.Z);

                                            await control.SetDoBit(0, mc.MC_GPO, 1, 0);

                                            globalStatus.IsRunning = true; ;
                                        }
                                    }

                                    main.Show();
                                    this.Close();
                                }
                                else
                                {
                                    main.Show();
                                    this.Close();
                                    //MessageBox.Show("找不到控制板卡");
                                    //Application.Current.Shutdown();
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("软件使用期限已到");
                            Application.Current.Shutdown();
                        }
                    }
                    else
                    {
                        MessageBox.Show("找不到加密狗");
                        Application.Current.Shutdown();
                    }
#endif

                });
            }
        }
    }
}
